package com.newbie.iSee;

import java.io.*;
import java.net.*;
import java.util.*;

import android.content.Context;
import android.graphics.drawable.*;

public class Cache {
	private Context mContext;
	private Hashtable<String, Drawable> photoTable;
	private Hashtable<String, Drawable> soundTable;
	private final String photoPathBase;
	private final String photoUrlBase = "http://";
	private final String soundPathBase;
	private final String soundUrlBase = "http://";

	public Cache(Context context) {
		mContext = context;
		photoPathBase = mContext.getCacheDir() + "/photos";
		soundPathBase = mContext.getCacheDir() + "/sounds";
	}

	private void transfer(InputStream in, OutputStream out) throws IOException {
		byte[] buffer = new byte[256];
		int size;
		while ((size = in.read(buffer)) > 0) {
			out.write(buffer, 0, size);
		}
		out.flush();
		out.close();
		in.close();
	}

	public Drawable getPhoto(String pid) throws MalformedURLException,
			IOException {
		Drawable photo;

		photo = (Drawable) photoTable.get(pid);
		if (photo != null)
			return photo;

		File file = new File(photoPathBase, pid);
		if (!file.exists()) {
			InputStream in = (InputStream) new URL(photoUrlBase + pid)
					.getContent();
			FileOutputStream out = new FileOutputStream(file);
			transfer(in, out);
		}
		photo = Drawable.createFromPath(photoPathBase + "/" + pid);

		photoTable.put(pid, photo);

		return photo;
	}

	public Drawable getSound(String sid) throws MalformedURLException,
			IOException {
		Drawable photo;

		photo = (Drawable) soundTable.get(sid);
		if (photo != null)
			return photo;

		File file = new File(soundPathBase, sid);
		if (!file.exists()) {
			InputStream in = (InputStream) new URL(soundUrlBase + sid)
					.getContent();
			FileOutputStream out = new FileOutputStream(file);
			transfer(in, out);
		}
		photo = Drawable.createFromPath(soundPathBase + "/" + sid);

		photoTable.put(sid, photo);

		return photo;
	}
}
